package top;

import java.util.Stack;

/**
 * @author chenyw
 * @date 2022/7/19 11:02
 */
public class Top227calculate {
    public static void main(String[] args) {
        int calculate = new Top227calculate().calculate("3 / 2");
        System.out.println(calculate);
    }
    public int calculate(String s) {
        Stack<Integer> stack = new Stack();

        //关键：使用一个指针变量记录前一个运算符号
        char preSign = '+';
        int num = 0;
        for (int i = 0; i < s.length(); i++) {
            //需要考虑进位
            if (Character.isDigit(s.charAt(i))) {
                num = num * 10 + (s.charAt(i) - '0');
            }
            if (!Character.isDigit(s.charAt(i)) && s.charAt(i) != ' ' || i == s.length() - 1) {
                switch (preSign) {
                    case '+' :
                        stack.push(num);
                        break;
                    case '-' :
                        stack.push(-num);
                        break;
                    case '*' :
                        stack.push(stack.pop() * num);
                        break;
                    case '/' :
                        stack.push(stack.pop() / num);
                    default:
                        break;
                }
                preSign = s.charAt(i);
                num = 0;
            }
        }
        int res = 0;
        while (!stack.isEmpty()) {
            res += stack.pop();
        }
        return res;
    }
}
